package com.situ.orderingsystem.dao.impl;

import com.situ.orderingsystem.dao.LoginDAo;
import com.situ.orderingsystem.global.Global;
import com.situ.orderingsystem.model.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class  LoginDaoImpl implements LoginDAo {
    private final JdbcTemplate template = new JdbcTemplate(Global.getDataSource());
    @Override
    public User findByUsername(String username) {
        String sql = "select id,username,password from user where username = ?";
        List<User> user =template.query(sql,new BeanPropertyRowMapper<>(User.class),username);
       return  user.size() >0? user.get(0) : null;
    }

    @Override
    public Boolean update(User user, String username, String password) {
        String sql = "update user set username =? , password = ? where id = ?";
        List<Object> args = new ArrayList<>();
        if(!StringUtils.hasText(username)){
           return false;
        }
        args.add(username);
        if(!StringUtils.hasText(password)){
        return  false;
        }
        args.add(password);
        args.add(user.getId());
        int rows = template.update(sql,args.toArray() );
        return  rows > 0;

    }
}
